<script setup lang="tsx">
import {getUserListApi, createdUserApi, updatedUserApi, createdCodeApi, POWER, lockingAccountApi, unlockAccountApi, changeStatusApi, removeUserApi} from "@/apps/admin/api/admin/user";
import {useHttpPagingResult} from "@/hooks/http";
import {ref, h, defineAsyncComponent} from "vue"
import {TableColumn} from "@/components/AppTable/TableType";
import {usePopupComponent, usePopupForm} from "@/components/FunctionComponents";
import {auth} from "@/apps/admin/units/auth";
import {getTimestamp} from "@/units/time";

const timestamp = ref(getTimestamp())

const where = ref({
  id: "",
  nickname: "",
  status: "",
  is_super: ""
})

/**
 * 引入hooks
 */
const {pagination, list, loading, getRequestData} = useHttpPagingResult(function (query) {
  timestamp.value = getTimestamp()
  return getUserListApi({...query});
})

/**
 * 会员列配置
 */
const columns: Array<TableColumn> = [
  {prop: "id", label: "id", fixed: "left", minWidth: 110},
  {prop: "nickname", label: "昵称", fixed: "left", minWidth: 120},
  {prop: "account", label: "登录账号", fixed: "left", minWidth: 190},
  {label: "操作", type: "action", fixed: "left", width: 140, align: "center"},
  {prop: "department", label: "部门", type: "json", property: "name", minWidth: 120},
  {prop: "job", label: "职位", minWidth: 120, type: "json", property: "name"},
  {prop: "locking", label: "锁定", minWidth: 170},
  {prop: "avatar", label: "头像", type: "image", minWidth: 120},
  {prop: "is_super", label: "超级权限", minWidth: 110, render: (row: any) => row.is_super === true ? '是' : ''},
  {prop: "role", label: "角色", minWidth: 160, render: (row: any) => row.role?.join(',')},
  {prop: "status", label: "状态", minWidth: 120},
  {prop: "created_at", label: "创建时间", type: "timestramp", minWidth: 170},
  {prop: "updated_at", label: "最后编辑", type: "timestramp", minWidth: 170},
];

/**
 * 添加会员
 * @constructor
 */
function CreatedUser() {
  usePopupForm({
    api: createdUserApi,
    width: '640px',
    onSuccess: () => getRequestData()
  })
}

/**
 * 编辑账号
 */
async function updatedUser(id: number) {
  usePopupForm({
    api: updatedUserApi,
    query: {id},
    width: '640px',
    onSuccess: () => getRequestData()
  })
}


/**
 * 删除账号
 */
async function removeUser(id) {
  const result = await removeUserApi(id)
  if (result.code === 200) {
    getRequestData()
  }
}

/**
 * 创建授权码
 */
async function createdCode(row) {
  let {code, data} = await createdCodeApi(row.id)
  if (code === 200) {
    const component = h(defineAsyncComponent((): any => import("./components/ShowQrcodeData.vue")), {
      qrcode: data
    })
    await usePopupComponent("授权码信息", component, '420px')
  }
}


/**
 * 锁定账号
 */
async function lockingAccount(id: number) {
  const result = await lockingAccountApi(id)
  if (result.code === 200) {
    getRequestData()
  }
}


/**
 * 解锁账号
 */
async function unlockAccount(id: number) {
  const result = await unlockAccountApi(id)
  if (result.code === 200) {
    getRequestData()
  }
}

/**
 * 启用,禁用账号
 * @constructor
 */
async function ChangeStatus(value: any, row: any, index: number) {
  changeStatusApi(row.id, value).then(res => {
    if (res.code === 200) {
      list.value[index].status = value
    }
  })
}
</script>

<template>
  <div>
    <data-card class="app-margin-bottom-interval">
      <search-form :disabled="loading" label-width="80px" @search="getRequestData({page:1,size:pagination.size})">
        <template #default>
          <el-form-item label="管理员ID">
            <el-input clearable v-model="where.id" placeholder="管理员账号ID"/>
          </el-form-item>
          <el-form-item label="名称">
            <el-input clearable v-model="where.nickname" placeholder="管理员名称"/>
          </el-form-item>
        </template>
        <template #more>
          <el-form-item label="状态">
            <el-radio-group v-model="where.status">
              <el-radio-button label="">全部</el-radio-button>
              <el-radio-button label="1">使用中</el-radio-button>
              <el-radio-button label="0">已禁用</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="超级权限">
            <el-radio-group v-model="where.is_super">
              <el-radio-button label="">全部</el-radio-button>
              <el-radio-button label="1">是</el-radio-button>
              <el-radio-button label="0">否</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </template>
      </search-form>
    </data-card>
    <data-card title="系统管理员">
      <template #right>
        <el-space>
          <admin-auth :sign="POWER.CREATED">
            <el-button size="small" @click="CreatedUser" type="primary">添加</el-button>
          </admin-auth>
          <el-button size="small" type="success" :loading="loading" @click="getRequestData({page:pagination.page,size:pagination.size})">
            刷新
          </el-button>
        </el-space>
      </template>
      <app-table height="calc(var(--ach) - 170px)" class="app-margin-top-interval" :data="list" :columns="columns">
        <template #account="{row}">
          <span v-copy>{{ row.account }}</span>
        </template>
        <template #status="{row,$index}">
          <admin-auth :sign="POWER.UPDATED">
            <app-switch :model-value="row.status" @change="ChangeStatus($event,row,$index)"></app-switch>
            <template #fail>
              <app-switch :model-value="row.status" disabled></app-switch>
            </template>
          </admin-auth>
        </template>
        <template #locking="{row}">
          <span v-if="row.locking>timestamp">
            <el-space>
              <el-text type="danger">锁定中</el-text>
              <admin-auth :sign="POWER.UNLOCK">
                  <el-tooltip content="解锁账号">
                    <svg-icon @click="unlockAccount(row.id)" color="#28b72e" class="app-vertical-middle app-tap" name="unlock" :size="18"></svg-icon>
                  </el-tooltip>
              </admin-auth>
            </el-space>
          </span>
          <span v-else>
            <el-space>
              <el-text type="success">使用中</el-text>
              <admin-auth :sign="POWER.LOCKING">
                <el-tooltip content="锁定账号">
                  <svg-icon @click="lockingAccount(row.id)" color="#ff0000" class="app-vertical-middle app-tap" name="lock" :size="18"></svg-icon>
                </el-tooltip>
              </admin-auth>
            </el-space>
          </span>
        </template>
        <template v-if="auth([POWER.CODE,POWER.UPDATED,POWER.REMOVE])" #action="{row}">
          <el-space>
            <operate-link @tap="createdCode(row)" :disabled="!auth(POWER.CODE)">
              授权码
            </operate-link>
            <operate-link :disabled="!auth(POWER.UPDATED)" @tap="updatedUser(row.id)">
              编辑
            </operate-link>
            <operate-link :disabled="!auth(POWER.REMOVE)" confirm="确定要删除此账号吗?" @tap="removeUser(row.id)">
              删除
            </operate-link>
          </el-space>
        </template>
      </app-table>
    </data-card>
  </div>
</template>